﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using System.Reflection;
using DataInfo;
using System.Security.Cryptography;
using System.Text;
using KenLib.BusinessManager;

/// <summary>
/// Summary description for Common
/// </summary>
public class AppCode_Common
{
    public AppCode_Common()
    {
        //
        // TODO: Add constructor logic here
        //
    }
    public static string GetUserName(string ID)
    {
        List<基本情報> lst = new GlobalManager().GetInfoInTableByValue<基本情報>("基本情報", "社員ID", ID, true);
        if (lst.Count > 0)
        {
            return lst[0].姓 + " " + lst[0].名;
        }
        return "0";
    }
    public static void AddHistory(System.Web.UI.Page page)
    {
        List<String> lsHistory;
        if (page.Session["history"] == null)
            lsHistory = new List<string>();
        else
            lsHistory = (List<String>)page.Session["history"];
        lsHistory.Add(page.AppRelativeVirtualPath.Substring(2));
        page.Session["history"] = lsHistory;
    }
    public static string getHistory(System.Web.UI.Page page)
    {
        string strMainMenu = "frm_MainMenu.aspx";
        List<String> lsHistory;
        if (page.Session["history"] == null)
            return strMainMenu;
        lsHistory = (List<String>)page.Session["history"];
        if (lsHistory.Count > 0)
        {
            lsHistory.RemoveAt(lsHistory.Count - 1);
            if (lsHistory.Count > 0)
            {
                string strPageBack = lsHistory[lsHistory.Count - 1];
                lsHistory.RemoveAt(lsHistory.Count - 1);
                page.Session["history"] = lsHistory;
                return strPageBack;
            }
        }
        return strMainMenu;
    }
    public static object getValue(PropertyInfo infoProperty, TextBox txt)
    {
        object objReturn = null;
        if (txt.Text != "")
        {
            string fullName = infoProperty.PropertyType.Name;
            if (infoProperty.PropertyType.Name.Contains("Nullable"))
            {
                fullName = infoProperty.PropertyType.FullName;
                fullName = fullName.Substring(fullName.IndexOf("[[System.") + "[[System.".Length);
                fullName = fullName.Substring(0, fullName.IndexOf(","));
            }
            switch (fullName)
            {
                case "String":
                    objReturn = txt.Text;
                    break;
                case "Int32":
                    objReturn = Convert.ToInt32(txt.Text);
                    break;
                case "DateTime":
                    objReturn = Convert.ToDateTime(txt.Text);
                    break;
            }
        }
        return objReturn;
    }
    public static bool Validation(Control Page, HtmlGenericControl div, string strTextBoxNotRequireValue)
    {
        bool bValid = true;
        foreach (Control c in div.Controls)
        {
            if (c.GetType().Name.IndexOf("LiteralControl") == -1)
            {
                string strErr = "";
                if (c.GetType().Name == "HtmlGenericControl" && c.Controls.Count > 1)
                {
                    Control t = c.Controls[1];
                    strErr = CheckValueOfTextBox(t, strTextBoxNotRequireValue);
                    if (strErr != "")
                    {
                        ScriptManager.RegisterStartupScript(Page, Page.GetType(), "show", "alert('" + strErr + "');", true);
                        return false;
                    }
                }
                strErr = CheckValueOfTextBox(c, strTextBoxNotRequireValue);
                if (strErr != "")
                {
                    ScriptManager.RegisterStartupScript(Page, Page.GetType(), "show", "alert('" + strErr + "');", true);
                    return false;
                }

                else if (c.GetType().Name == "DropDownList")
                {
                    if (((DropDownList)c).SelectedValue == "" || ((DropDownList)c).SelectedValue == "-1")
                    {
                        ScriptManager.RegisterStartupScript(Page, Page.GetType(), "show", "alert('" + c.ID.Substring(3) + "');", true);
                        c.Focus();
                        return false;
                    }
                }
            }
            //else if (c.GetType().Name == "CheckBox")
            //    ((CheckBox)c).Checked = false;
            //else if (c.GetType().Name == "RadioButton")
            //    ((RadioButton)c).Checked = false;
        }
        return bValid;
    }
    public static string CheckValueOfTextBox(Control c,string strTextBoxNotRequireValue)
    {
        string strResturn = "";
        string strIdControl = c.ID.Length > 3 ? c.ID.Substring(3) + " " : "";
        if (c.GetType().Name == "TextBox")
        {
            if (strTextBoxNotRequireValue.IndexOf(strIdControl) == -1 && ((TextBox)c).Text == "")
            {
                strResturn = strIdControl.Substring(1) + "を選択してください。";
                c.Focus();
            }
        }
        return strResturn;
    }
    public static void VisibleControl(Control control,string strControlsVisible)
    {
        string[] arrStrNames = strControlsVisible.Split(',');
        foreach (string strName in arrStrNames)
        {
            Control c = control.FindControl("div" + strName.Trim());
            if (c != null)
                c.Visible = false;
        }
    }
    public static void ShowEmtyGrid<T>(GridView grv, int iNumberColumn, string strTextShow, string strCssClass) where T : XBLib.BusinessObject.BindableBusinessObject, new()
    {
        List<T> ls = new List<T>();
        ls.Add(new T());
        grv.ShowFooter = false;
        grv.DataSource = ls;
        grv.DataBind();
        //iNumberColumn = grv.Columns.Count;
        grv.Rows[0].Cells.Clear();
        TableCell cell = new TableCell();
        cell.ColumnSpan = grv.Columns.Count;
        cell.Text = strTextShow;
        if (!string.IsNullOrEmpty(strCssClass))
            cell.CssClass = strCssClass;
        grv.Rows[0].Cells.Add(cell);

    }
    public static void Show10Row(GridView grv,  string strTableHeader, string strValueInFirstRow) 
    {
        DataTable dt = new DataTable();
        string[] arrColumnNames = strTableHeader.Split(',');
        string[] arrFristRowValues = strValueInFirstRow.Split(',');
        foreach (string str in arrColumnNames)
        {
            dt.Columns.Add(str);
        }
        for (int i = 0; i < 9; i++)
        {
            dt.Rows.InsertAt(dt.NewRow(),0);
            dt.Rows[0][0] = "----";
        }
        DataRow r = dt.NewRow();
        for (int i = 0; i < arrColumnNames.Length; i++)
        {
            if (i < arrFristRowValues.Length)
                r[arrColumnNames[i]] = arrFristRowValues[i];
        }
        dt.Rows.InsertAt(r,0);
        grv.DataSource = dt;
        grv.DataBind();
    }
    public static string Encrypt(string toEncrypt, bool useHashing)
    {
        byte[] keyArray;
        byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);

        System.Configuration.AppSettingsReader settingsReader = new AppSettingsReader();
        // Get the key from config file
        string key = "xanhbiec";
        //System.Windows.Forms.MessageBox.Show(key);
        if (useHashing)
        {
            MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
            keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
            hashmd5.Clear();
        }
        else
            keyArray = UTF8Encoding.UTF8.GetBytes(key);

        TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
        tdes.Key = keyArray;
        tdes.Mode = CipherMode.ECB;
        tdes.Padding = PaddingMode.PKCS7;

        ICryptoTransform cTransform = tdes.CreateEncryptor();
        byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
        tdes.Clear();
        return Convert.ToBase64String(resultArray, 0, resultArray.Length);
    }
    /// <summary>
    /// DeCrypt a string using dual encryption method. Return a DeCrypted clear string
    /// </summary>
    /// <param name="cipherString">encrypted string</param>
    /// <param name="useHashing">Did you use hashing to encrypt this data? pass true is yes</param>
    /// <returns></returns>
    public static string Decrypt(string cipherString, bool useHashing)
    {
        byte[] keyArray;
        byte[] toEncryptArray = Convert.FromBase64String(cipherString);

        System.Configuration.AppSettingsReader settingsReader = new AppSettingsReader();
        //Get your key from config file to open the lock!
        string key = "xanhbiec";

        if (useHashing)
        {
            MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
            keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
            hashmd5.Clear();
        }
        else
            keyArray = UTF8Encoding.UTF8.GetBytes(key);

        TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
        tdes.Key = keyArray;
        tdes.Mode = CipherMode.ECB;
        tdes.Padding = PaddingMode.PKCS7;

        ICryptoTransform cTransform = tdes.CreateDecryptor();
        byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

        tdes.Clear();
        return UTF8Encoding.UTF8.GetString(resultArray);
    }
    public static object CountBytes(string value)
    {
        Int32 result = 0;
        Encoding instance = default(Encoding);
        instance = Encoding.GetEncoding("SHIFT-JIS");
        result = instance.GetBytes(value.Trim()).Length;
        return result;
    }
    public static int getPageSize()
    {
        string iPagesize = ConfigurationManager.AppSettings.Get("pagesize");
        return Convert.ToInt32(iPagesize);
    }
}
